package com.spdd.mt.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.spdd.mt.biz.config.dynamic.DynamicTableData;
import com.spdd.mt.biz.constant.NotifyStatus;
import com.spdd.mt.biz.constant.OrderStatus;
import com.spdd.mt.biz.constant.ReorderStatus;
import com.spdd.mt.biz.entity.MtRechargeOrderEntity;
import com.spdd.mt.biz.mapper.MtRechargeOrderMapper;
import com.spdd.mt.biz.service.MtRechargeOrderService;
import com.spdd.mt.biz.vo.StatisticRechargeBean;
import com.spdd.mt.common.base.impl.BaseServiceImpl;
import com.spdd.mt.common.util.DateUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * MtRechargeOrder 充值订单表  服务实现类
 * </p>
 *
 * @author shanfeilong
 * @since 2025-04-02
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class MtRechargeOrderServiceImpl extends BaseServiceImpl<MtRechargeOrderMapper, MtRechargeOrderEntity> implements MtRechargeOrderService {

    @Override
    public MtRechargeOrderEntity getById(String month, Long id) {
        if (id == null) {
            return null;
        }
        // 设置表月份
        DynamicTableData.setRequestData(new HashMap<>() {{
            put("month", month);
        }});

        return this.getById(id);
    }

    @Override
    public MtRechargeOrderEntity getByOrderNo(String orderNo) {
        LambdaQueryWrapper<MtRechargeOrderEntity> wrapper = new QueryWrapper<MtRechargeOrderEntity>().lambda()
                .eq(MtRechargeOrderEntity::getOrderNo, orderNo);
        MtRechargeOrderEntity entity = baseMapper.selectOne(wrapper);
        if (Objects.isNull(entity)) {
            log.info("当前月份表未查得，查询上月分表");

            // 设置表月份
            DynamicTableData.setRequestData(new HashMap<>() {{
                put("month", DateUtils.getLastMonth());
            }});

            entity = baseMapper.selectOne(wrapper);
        }
        if (Objects.nonNull(entity)) {
            return entity;
        }
        return null;
    }

    @Override
    public MtRechargeOrderEntity getByMtOrderNo(String mtOrderNo) {
        LambdaQueryWrapper<MtRechargeOrderEntity> wrapper = new QueryWrapper<MtRechargeOrderEntity>().lambda()
                .eq(MtRechargeOrderEntity::getMtOrderNo, mtOrderNo);
        MtRechargeOrderEntity entity = baseMapper.selectOne(wrapper);
        if (Objects.isNull(entity)) {
            log.info("当前月份表未查得，查询上月分表");

            // 设置表月份
            DynamicTableData.setRequestData(new HashMap<>() {{
                put("month", DateUtils.getLastMonth());
            }});

            entity = baseMapper.selectOne(wrapper);
        }
        if (Objects.nonNull(entity)) {
            return entity;
        }
        return null;
    }

    @Override
    public boolean save(MtRechargeOrderEntity entity, String month) {
        if (Objects.isNull(entity)) {
            return false;
        }
        // 设置表月份
        DynamicTableData.setRequestData(new HashMap<>() {{
            put("month", month);
        }});
        return save(entity);
    }

    @Override
    public boolean updateById(MtRechargeOrderEntity entity, String month, Long id) {
        // 设置表月份
        DynamicTableData.setRequestData(new HashMap<>() {{
            put("month", month);
        }});

        return update(entity, new QueryWrapper<MtRechargeOrderEntity>().lambda()
                .eq(MtRechargeOrderEntity::getId, id));
    }

    @Override
    public void updateReorder(String month, Long id, Integer reorderStatus, Date lastReorderTime) {

        // 设置表月份
        DynamicTableData.setRequestData(new HashMap<>() {{
            put("month", month);
        }});

        MtRechargeOrderEntity entity = getById(id);
        if (Objects.isNull(entity)) {
            log.info("标记为代重发失败，订单不存在，id = {}", id);
            return;
        }

        MtRechargeOrderEntity updateEntity = new MtRechargeOrderEntity();
        updateEntity.setReorderStatus(reorderStatus);
        if (Objects.nonNull(lastReorderTime)) {
            updateEntity.setReorderTimes(entity.getReorderTimes() + 1);
            updateEntity.setLastReorderTime(lastReorderTime);
        }
        update(updateEntity, new QueryWrapper<MtRechargeOrderEntity>().lambda()
                .eq(MtRechargeOrderEntity::getMtOrderNo, entity.getMtOrderNo()));


        // update dy_mobile_recharge_${month}
        // set reorder_status = #{reorderStatus}
        // <if test="lastReorderTime != null">
        //         ,reorder_times = reorder_times + 1
        //         ,last_reorder_time = #{lastReorderTime}
        // </if>
        // where charge_no = #{chargeNo}
        //
        // int updateReorder (
        //         @Param("month") String month,
        //         @Param("reorderStatus") Integer reorderStatus,
        //         @Param("lastReorderTime") String lastReorderTime,
        //         @Param("chargeNo") String chargeNo);


        // @Override
        // public boolean  updateReorder(String month, Integer reorderStatus, String lastReorderTime, String chargeNo) {
        //
        //     update dy_mobile_recharge_${month}
        //     set reorder_status = #{reorderStatus}
        // <if test="lastReorderTime != null">
        //             ,reorder_times = reorder_times + 1
        //             ,last_reorder_time = #{lastReorderTime}
        // </if>
        //     where charge_no = #{chargeNo}
        //
        // }
    }

    @Override
    public List<MtRechargeOrderEntity> getNeedNotify(String month, String lastTime, Integer notifyTimes) {

        // 设置表月份
        DynamicTableData.setRequestData(new HashMap<>() {{
            put("month", month);
        }});

        return list(new QueryWrapper<MtRechargeOrderEntity>().lambda()
                .in(MtRechargeOrderEntity::getNotifyStatus, Arrays.asList(NotifyStatus.INIT.getValue(), NotifyStatus.FAILED.getValue()))
                .in(MtRechargeOrderEntity::getOrderStatus, Arrays.asList(OrderStatus.SUCCESS.getValue(),
                        OrderStatus.FAILED.getValue(), OrderStatus.REEXCHANGE.getValue()))
                .lt(MtRechargeOrderEntity::getLastNotifyTime, lastTime)
                .lt(Objects.nonNull(notifyTimes), MtRechargeOrderEntity::getNotifyTimes, notifyTimes)
        );
    }

    @Override
    public List<MtRechargeOrderEntity> getNeedReOrder(String month, String tradeDate, Integer maxReorderTimes, String startTime, String endTime, Integer count) {

        // 设置表月份
        DynamicTableData.setRequestData(new HashMap<>() {{
            put("month", month);
        }});

        return list(new QueryWrapper<MtRechargeOrderEntity>().lambda()
                .eq(MtRechargeOrderEntity::getTradeDate, tradeDate)
                .eq(MtRechargeOrderEntity::getReorderStatus, ReorderStatus.WAIT.getValue())
                .eq(MtRechargeOrderEntity::getOrderStatus, OrderStatus.PROCESSING.getValue())
                .lt(MtRechargeOrderEntity::getReorderTimes, maxReorderTimes)
                .ge(MtRechargeOrderEntity::getCreateTime, startTime)
                .le(MtRechargeOrderEntity::getCreateTime, endTime)
                .orderByAsc(MtRechargeOrderEntity::getId).last("limit " + count)
        );
    }

    @Override
    public List<MtRechargeOrderEntity> getFinishByDayAndMerchNo(String month, Integer day, String merchNo) {

        // 设置表月份
        DynamicTableData.setRequestData(new HashMap<>() {{
            put("month", month);
        }});

        return list(new QueryWrapper<MtRechargeOrderEntity>().lambda()
                .eq(MtRechargeOrderEntity::getFinishDate, day)
                .eq(MtRechargeOrderEntity::getMerchNo, merchNo)
                .in(MtRechargeOrderEntity::getOrderStatus, Arrays.asList(OrderStatus.SUCCESS.getValue(),
                        OrderStatus.FAILED.getValue(), OrderStatus.REEXCHANGE.getValue()))
        );
    }

    @Override
    public List<StatisticRechargeBean> getSuccessStatistic(String month, String txnDate, String appId) {
        return baseMapper.getSuccessStatistic(month, txnDate, appId);
    }

    @Override
    public List<StatisticRechargeBean> getTotalStatistic(String month, String txnDate, String appId) {
        return baseMapper.getTotalStatistic(month, txnDate, appId);
    }

    @Override
    public List<StatisticRechargeBean> getRateStatistic(String month, String txnDate, Integer time, String appId) {
        return baseMapper.getRateStatistic(month, txnDate, time, appId);
    }


    @Override
    public boolean updateNotify(Long id, String month, Integer notifyStatus, Date lastNotifyTime) {
        // 设置表月份
        DynamicTableData.setRequestData(new HashMap<>() {{
            put("month", month);
        }});

        MtRechargeOrderEntity updateEntity = new MtRechargeOrderEntity();
        updateEntity.setId(id);
        updateEntity.setNotifyStatus(notifyStatus);
        updateEntity.setLastNotifyTime(lastNotifyTime);

        LambdaUpdateWrapper<MtRechargeOrderEntity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.setSql("notify_times=notify_times+1");
        wrapper.eq(MtRechargeOrderEntity::getId, id);

        return baseMapper.update(updateEntity, wrapper) > 0;

    }


    // private QueryWrapper<MtRechargeOrderEntity> getWrapper(Map<String, Object> params) {
    //     QueryWrapper<MtRechargeOrderEntity> wrapper = new QueryWrapper<>();
    //
    //     String id = (String) params.get("id");
    //     wrapper.lambda().eq(StrUtil.isNotBlank(id), MtRechargeOrderEntity::getId, id);
    //
    //     List<Long> ids = (List<Long>) params.get("ids");
    //     wrapper.lambda().in(CollectionUtil.isNotEmpty(ids), MtRechargeOrderEntity::getId, ids);
    //
    //     // wrapper.lambda().eq(MtRechargeOrderEntity::getIsDelete, 0);
    //
    //     return wrapper;
    // }
    //
    // @Override
    // public Page<MtRechargeOrderVo> page(Map<String, Object> map) {
    //     Page<MtRechargeOrderEntity> pageObj = this.getPage(map);
    //     Page<MtRechargeOrderEntity> pageList = this.page(pageObj, getWrapper(map));
    //
    //     return convertTarget(pageList, MtRechargeOrderVo.class);
    // }
    //
    // @Override
    // public List<MtRechargeOrderVo> list(Map<String, Object> map) {
    //
    //     List<MtRechargeOrderEntity> list = this.list(getWrapper(map));
    //
    //     return convertTarget(list, MtRechargeOrderVo.class);
    // }
    //
    // @Override
    // public MtRechargeOrderVo get(Long id) {
    //     if (id == null) {
    //         return null;
    //     }
    //     MtRechargeOrderEntity entity = this.getById(id);
    //
    //     return convertTarget(entity, MtRechargeOrderVo.class);
    // }
    //
    // @Override
    // @Transactional(rollbackFor = Exception.class)
    // public void save(MtRechargeOrderVo dto) {
    //     MtRechargeOrderEntity entity = ConvertUtils.sourceToTarget(dto, MtRechargeOrderEntity.class);
    //
    //     dto.setId(null);
    //     this.save(entity);
    //
    //     dto.setId(entity.getId());
    // }
    //
    // @Override
    // @Transactional(rollbackFor = Exception.class)
    // public void update(MtRechargeOrderVo dto) {
    //     if (dto.getId() == null) {
    //         throw new BaseException("主键为空");
    //     }
    //
    //     MtRechargeOrderEntity entity = ConvertUtils.sourceToTarget(dto, MtRechargeOrderEntity.class);
    //     this.updateById(entity);
    // }
}
